﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace CommonProject.Common
{
    public static class FileExtensions
    {
        /// <summary>
        /// 获取文件路径
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static string GetFilePath(this string filename)
        {
            if (string.IsNullOrWhiteSpace(filename)) 
            {
                return null;
            }
            string path = Path.GetDirectoryName(filename);
            return path;
        }

        /// <summary>
        /// 文件保存前，先创建文件路径
        /// </summary>
        /// <param name="filename"></param>
        public static void CreateFilePath(this string filename)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                return;
            }
            string path = filename.GetFilePath();
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static string GetFileExtname(this string filename)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                return null;
            }
            return Path.GetExtension(filename);
        }

        /// <summary>
        /// 获取文件内容
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string GetFileContent(this string filename, Encoding encoding = null)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                return null;
            }
            if (encoding == null)
                encoding = Encoding.UTF8;
            return File.ReadAllText(filename, encoding);
        }
    }
}